﻿using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.CommonModels;
using Ekton_Manage_DTO.RequestModels.SysRolePermission;
using Ekton_Manage_DTO.RequestModels.User;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Ekton_Manage_Business
{
    public class SelectSysUserInfo : ISelectSysUser
    {
        private readonly SerializeParameter _serialize;
        private readonly IBaseRepository<system_log, int> _basesyslogRepository;
        private readonly IBaseRepository<sys_user, int> _basesysuserRepository;
        private readonly IBaseRepository<sys_role, int> _basesysroleRepository;
        private readonly IBaseRepository<sys_role_permission, int> _basesyspermissionRepository;
        private readonly IBaseRepository<sys_permission, int> _basepermissionRepository;
        private readonly IBaseRepository<user_roleView, int> _baseuserRoleViewRepository;
        private readonly IBaseRepository<company_email, int> _basecompanymsgRepository;
        private readonly IBaseRepository<copyright, int> _basecopyrightRepository;
        private readonly IBaseRepository<menu_btn, int> _basemenubtnRepository;
        public SelectSysUserInfo(IBaseRepository<copyright, int> basecopyrightRepository, SerializeParameter serialize, IBaseRepository<sys_user, int> basesysuserRepository, IBaseRepository<system_log, int> basesyslogRepository, IBaseRepository<sys_role, int> basesysroleRepository, IBaseRepository<sys_permission, int> basepermissionRepository, IBaseRepository<sys_role_permission, int> basesyspermissionRepository, IBaseRepository<user_roleView, int> baseuserRoleViewRepository, IBaseRepository<company_email, int> basecompanymsgRepository, IBaseRepository<menu_btn, int> basemenubtnRepository)
        {
            _serialize = serialize;
            _basesysuserRepository = basesysuserRepository;
            _basesyslogRepository = basesyslogRepository;
            _basesysroleRepository = basesysroleRepository;
            _basepermissionRepository = basepermissionRepository;
            _basesyspermissionRepository = basesyspermissionRepository;
            _baseuserRoleViewRepository = baseuserRoleViewRepository;
            _basecompanymsgRepository = basecompanymsgRepository;
            _basecopyrightRepository = basecopyrightRepository;
            _basemenubtnRepository = basemenubtnRepository;
        }

        private bool isInto = false;
        private List<sys_permission> roleMenu = new();
        private List<menu_btn> menuBtns = new();
        /// <summary>
        /// 菜单动态路由
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<object> GetMenuRouter(int id, int role)
        {
            if (!isInto)
            {
                //通过前端用户的role_id来查询角色权限菜单表(sys_role =>sys_role_permission)
                var rolePerimissId = (await _basesyspermissionRepository.QueryTableList(m => m.role_id == role)).Select(m => m.permission_id).ToList();
                //通过角色权限菜单表查菜单表的id  (sys_role_permission => sys_permission)
                roleMenu = await _basepermissionRepository.QueryTableList(m => rolePerimissId.Contains(m.id));
                id = 0;
            }

            var menu = roleMenu.Where(x => x.pid == id && x.type != 3);
            isInto = true;
            var list = new List<dynamic>();
            foreach (var item in menu)
            {
                //meta字段
                var meta = new
                {
                    icon = item.icon,
                    title = item.title
                };
                list.Add(new
                {
                    path = item.path,
                    name = item.name,
                    title = item.name,
                    component = item.component,
                    redirect = item.redirect,
                    meta = meta,
                    order_num = item.order_num,
                    children = await this.GetMenuRouter(item.id, 0)
                });
            }
            return list;
        }

        /// <summary>
        /// 菜单动态路由
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //public async Task<object> GetMenuRouter(int id)
        //{
        //if (!isInto)
        //{
        //    //通过前端用户的role_id来查询角色权限菜单表(sys_role =>sys_role_permission)
        //    //var rolePerimissId = (await _basesyspermissionRepository.QueryTableList(m => m.role_id == role)).Select(m => m.permission_id).ToList();
        //    //通过角色权限菜单表查菜单表的id  (sys_role_permission => sys_permission)
        //    roleMenu = await _basepermissionRepository.QueryTableList(m => true && m.type != 3);//只查询一二级菜单
        //    menuBtns = await _basemenubtnRepository.QueryTableList(m => true);
        //    id = 0;
        //    isInto = true;
        //}

        //var menu = roleMenu.Where(x => x.pid == id);
        //var list = new List<dynamic>();
        //var childrenBtnData = new List<dynamic>();//按钮
        //foreach (var item in menu)
        //{
        //    var btn = menuBtns.Where(m => m.menuId == item.id).ToList();
        //    btn.ForEach((m) =>
        //    {
        //        childrenBtnData.Add(new
        //        {
        //            btnCode = m.btnCode,
        //            btnName = m.btnName
        //        });
        //    });
        //    list.Add(new
        //    {
        //        path = item.path,
        //        name = item.name,
        //        title = item.name,
        //        component = item.component,
        //        redirect = item.redirect,
        //        order_num = item.order_num,
        //        btn = childrenBtnData,
        //        children = await this.GetMenuRouter(item.id)
        //    });
        //}
        //return list; 
        //    return new object();
        //}

        List<dynamic> exisList = new();
        /// <summary>
        /// 查询菜单结构
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<object> GetMenuList(int id)
        {
            if (!isInto)
            {
                //通过前端用户的role_id来查询角色权限菜单表(sys_role =>sys_role_permission)
                //var rolePerimissId = (await _basesyspermissionRepository.QueryTableList(m => m.role_id == role)).Select(m => m.permission_id).ToList();
                //通过角色权限菜单表查菜单表的id  (sys_role_permission => sys_permission)
                roleMenu = await _basepermissionRepository.QueryTableList(m => true && m.type != 3);//只查询一二级菜单
                menuBtns = await _basemenubtnRepository.QueryTableList(m => true);
                id = 0;
                isInto = true;
            }

            var menu = roleMenu.Where(x => x.pid == id);
            var list = new List<dynamic>();
            foreach (var item in menu)
            {
                list.Add(new
                {
                    id = item.id,
                    name = item.name,
                    order_num = item.order_num,
                    btn = menuBtns.Where(m => m.menuId == item.id).ToList().Select(x => new
                    {
                        btnCode = x.btnCode,
                        btnName = x.btnName
                    }),
                    children = await this.GetMenuList(item.id)
                });
            }
            return list;
        }



        /// <summary>
        /// 获取选中的菜单权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<object> GetMenuPower(int id)
        {
            var rolePerimissId = (await _basesyspermissionRepository.QueryTableList(m => m.role_id == id && m.sign == 1)).Select(m => m.permission_id).ToList();
            var result = new List<dynamic>();
            var temp = await _basesysroleRepository.QuerySingleData(id);
            result.Add(new
            {
                checkMenuIds = rolePerimissId,
                checkBtnCodes = temp.btnCodes
            });
            return result;
        }


        /// <summary>
        /// 查询全部角色
        /// </summary>
        public async Task<Tuple<List<sys_role>, int>> GetSysRolesInfo(QueryDataParame query)
        {
            var dicData = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<sys_role, bool>> expression = m => true;
            if (dicData.ContainsKey("rolename") && !string.IsNullOrEmpty(dicData["rolename"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.rolename.Contains(dicData["rolename"].ToString()));
            }
            var result = await _basesysroleRepository.QueryPageData(query, expression);
            return result;
        }

        /// <summary>
        /// 查询全部操作日志
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<Tuple<List<system_log>, int>> GetSysLogList(QueryDataParame query)
        {
            var dicData = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<system_log, bool>> expression = m => true;
            if (dicData.ContainsKey("create_op_name") && !string.IsNullOrEmpty(dicData["create_op_name"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.create_op_name.Contains(dicData["create_op_name"].ToString()));
            }
            if (dicData.ContainsKey("oper_type") && !string.IsNullOrEmpty(dicData["oper_type"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.oper_type.Contains(dicData["oper_type"].ToString()));
            }
            if (dicData.ContainsKey("create_op_date") && !string.IsNullOrEmpty(dicData["create_op_date"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.create_op_date >= dicData["create_op_date"].ObjToDate() && m.create_op_date <= dicData["create_op_date"].ObjToDate().AddDays(1));
            }
            var result = await _basesyslogRepository.QueryPageData(query, expression);
            return result;
        }

        /// <summary>
        /// 查询全部账号
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<Tuple<List<user_roleView>, int>> GetSysUserList(QueryDataParame query)
        {
            var dicData = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<user_roleView, bool>> expression = m => true;
            if (dicData.ContainsKey("account") && !string.IsNullOrEmpty(dicData["account"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.account.Contains(dicData["account"].ToString()));
            }
            if (dicData.ContainsKey("name") && !string.IsNullOrEmpty(dicData["name"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.name.Contains(dicData["name"].ToString()));
            }
            if (dicData.ContainsKey("company") && !string.IsNullOrEmpty(dicData["company"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.company.Contains(dicData["company"].ToString()));
            }
            if (dicData.ContainsKey("state") && !string.IsNullOrEmpty(dicData["state"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.state == dicData["state"].ObjToInt());
            }
            var result = await _baseuserRoleViewRepository.QueryPageData(query, expression);
            return result;
        }

        /// 
        /// <summary>
        /// 编辑账号信息
        /// </summary>
        /// 
        public async Task<Message> PutSysUserInfo(DtoInsertSysUser requset)
        {
            var sysUserList = await _basesysuserRepository.QuerySingleData(requset.id);
            if (sysUserList == null) return new Message(false, 202);
            sysUserList.account = requset.account;
            sysUserList.name = requset.name;
            sysUserList.phone = requset.phone;
            sysUserList.company = requset.company;
            sysUserList.sex = requset.sex;
            sysUserList.role = requset.role;
            sysUserList.email = requset.email;
            //只传role ，role通过role来查询
            var rolename = await _basesysroleRepository.QuerySingleData(m => m.id == requset.role);
            sysUserList.role_name = rolename.rolename;
            var result = await _basesysuserRepository.UpdateSingleData(sysUserList);
            return new Message(result.Item1);
        }
        /// <summary>
        /// 停用账号
        /// </summary>
        /// 
        public async Task<Message> PutSysUserState(int sysUserId)
        {
            var sysUserState = await _basesysuserRepository.QuerySingleData(sysUserId);
            if (sysUserState == null) return new Message(false, 202);
            if (sysUserState.state == 1)
            {
                sysUserState.state = 2;//用户停用
            }
            else if (sysUserState.state == 2)
            {
                sysUserState.state = 1;//取消禁用
            }
            var result = await _basesysuserRepository.UpdateSingleData(sysUserState);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 删除用户账号
        /// </summary>
        /// 
        public async Task<Message> DeleteSysUserInfo(int userId)
        {
            var result = await _basesysuserRepository.DeleteSingleData(userId);
            return new Message(result);
        }

        /// <summary>
        /// 重置账号密码
        /// </summary>
        /// 
        public async Task<Message> PutSysUserPwd(int userId)
        {
            var sysUserInfo = await _basesysuserRepository.QuerySingleData(userId);
            if (sysUserInfo == null) return new Message(false, 202);
            sysUserInfo.password = "123456";
            var result = await _basesysuserRepository.UpdateSingleData(sysUserInfo);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 编辑角色信息
        /// </summary>
        /// 
        public async Task<Message> PutSysRolesInfo(DtoInsertSysRole request)
        {
            var sysRoleList = await _basesysroleRepository.QuerySingleData(request.id);
            if (sysRoleList == null) return new Message(false, 202);
            sysRoleList.rolename = request.rolename;
            sysRoleList.roledescribe = request.roledescribe;
            var result = await _basesysroleRepository.UpdateSingleData(sysRoleList);
            return new Message(result.Item1);
        }

        /// <summary>
        /// 修改角色权限（用数组的形式传权限菜单的id）
        /// </summary>
        /// 
        public async Task<Message> PostSysUserPower(DtoSysUserPower request)
        {
            #region query munu
            var menuInfo = await _basepermissionRepository.QueryTableList(m => true);
            #endregion

            List<sys_role_permission> menuIds = new();
            var list = new List<sys_role_permission>();
            foreach (var item in request.permission)
            {
                //查出这个菜单的数据
                var menuData = menuInfo.Where(m => m.id == item).FirstOrDefault();
                //查看这个菜单是否有父级节点,将它的父级节点取出来
                if (menuData.pid != 0)
                {
                    var exisData = menuInfo.Where(m => m.id == menuData.pid).FirstOrDefault();

                    menuIds.Add(new sys_role_permission
                    {
                        role_id = request.roleId,
                        permission_id = item,
                        sign = 1
                    });
                    //向添加的角色写入对应的按钮编码btnCode
                    var insertBtnCode = await _basesysroleRepository.QuerySingleData(request.roleId);
                    insertBtnCode.btnCodes = request.btnCodes;
                    _ = await _basesysroleRepository.UpdateSingleData(insertBtnCode);
                    if (exisData != null)
                        menuIds.Add(new sys_role_permission
                        {
                            role_id = request.roleId,
                            permission_id = exisData.id,
                            sign = 0
                        });
                    //查看这个菜单是否有父级节点,将它的父级节点取出来
                    var endData = menuInfo.Where(m => m.id == exisData.pid).FirstOrDefault();
                    if (endData != null)
                        menuIds.Add(new sys_role_permission
                        {
                            role_id = request.roleId,
                            permission_id = endData.id,
                            sign = 0
                        });
                }
            }
            menuIds = menuIds.DistinctBy(m => m.permission_id).ToList();

            var selectRolePower = await _basesyspermissionRepository.QueryTableList(m => m.role_id == request.roleId);
            if (selectRolePower.Count > 0)
                await _basesyspermissionRepository.DeleteArray(selectRolePower.Select(m => m.id).ToList());
            var insertMany = await _basesyspermissionRepository.InsertManyData(menuIds);
            return new Message(true, 200);
        }


        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// 
        public async Task<Message> PostSysRolesInfo(DtoInsertSysRole request)
        {
            var list = await _basesysroleRepository.InsertSingleData(new sys_role
            {
                roledescribe = request.roledescribe,
                rolename = request.rolename
            });
            return new Message(list.Item1);
        }

        /// <summary>
        /// 添加账号信息
        /// </summary>
        /// 
        public async Task<Message> PostSysUserInfo(DtoInsertSysUser request)
        {
            var info = new sys_user
            {
                account = request.account,
                name = request.name,
                password = request.password,
                phone = request.phone,
                company = request.company,
                sex = request.sex,
                role = request.role,
                state = request.state,
                email = request.email
            };
            var rolename = await _basesysroleRepository.QuerySingleData(info.role);
            info.role_name = rolename.rolename;
            var list = await _basesysuserRepository.InsertSingleData(info);
            return new Message(list.Item1);
        }


        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// 
        public async Task<Message> DeleteSysRolesInfo(int id)
        {
            var userCount = await _basesysuserRepository.QueryCount(m=>m.role == id);
            if (userCount < 1)
            {
                var list = await _basesysroleRepository.DeleteSingleData(id);
                //删除角色信息的同时 删除他的权限菜单信息
                var selectRolePower = await _basesyspermissionRepository.QueryTableList(m => m.role_id == id);
                if (selectRolePower.Count > 0)
                    await _basesyspermissionRepository.DeleteArray(selectRolePower.Select(m => m.id).ToList());
                return new Message(true, 200);
            }
            else
            {
                return new Message("有用户正在使用该角色，请先分配好角色",false,202);
            }
        }

        /// <summary>
        /// 查询按钮url
        /// </summary>
        /// <returns></returns>
        public async Task<Message> GetBtnRouter()
        {
            var rolePerimissId = await _basepermissionRepository.QueryTableList(m => m.type == 3);
            string[] path = new string[] { };
            List<string> path_list = new List<string>();
            foreach (var item in rolePerimissId)
            {
                path_list.Add(item.url);
            }
            path = path_list.ToArray();
            return new Message(path);
        }

        /// <summary>
        /// 公司邮箱配置(通过平台id来修改公司邮箱)
        /// </summary>
        /// <param name="platform_id"></param>
        /// <param name="email"></param>
        /// <param name="auth_code"></param>
        /// <returns></returns>
        public async Task<Message> PostCompanyEmail(int platform_id, string email, string auth_code)
        {
            var platform = await _basecompanymsgRepository.QuerySingleData(m => m.platform_id == platform_id);
            platform.author_code = auth_code;//授权码
            platform.email = email;//邮箱
            var res = await _basecompanymsgRepository.UpdateSingleData(platform);
            return new Message(res);
        }

        /// <summary>
        /// 通过平台id来查看公司邮箱
        /// </summary>
        /// <param name="platform_id"></param>
        /// <returns></returns>
        public async Task<Message> GetCompanyEmail(int platform_id)
        {
            var res = await _basecompanymsgRepository.QuerySingleData(m => m.platform_id == platform_id);
            return new Message(res);
        }

        /// <summary>
        /// 查询底部版权栏信息
        /// </summary>
        /// <returns></returns>
        public async Task<Message> GetCopyRight()
        {
            var res = await _basecopyrightRepository.QueryTableList(m => true);
            return new Message(res);
        }

        //查看用户信息
        public async Task<Message> Getaccountn(int id)
        {
            var result = await _basesysuserRepository.QuerySingleData(id);
            if (result is null) return new Message("未找到该用户", false, 202);
            return new Message(result);
        }

        public async Task<Message> PutCopyRight(DtoCopyRight request)
        {
            var res = await _basecopyrightRepository.QuerySingleData(request.id);
            if (res is null) return new Message("没有该底部版权栏信息", false, 202);
            res.copyright_info = request.copyright_info;
            res.copyright_notice = request.copyright_notice;
            var results = await _basecopyrightRepository.UpdateSingleData(res);
            return new Message(results);
        }

        //查看用户信息
        public async Task<sys_user> GetUser(int id)
        {
            return await _basesysuserRepository.QuerySingleData(m => m.id == id);
        }
        /// <summary>
        /// 获取按钮编码
        /// </summary>
        /// <param name="id"></param>
        /// <remarks>
        /// id为用户id
        /// </remarks>
        /// <returns></returns>
        public async Task<Message> GetBtnCodes(int id)
        {
            var userInfo = await _basesysuserRepository.QuerySingleData(m => m.id == id);
            if (userInfo == null) return new Message(false, 202);
            //获取btnCode
            var RoleInfo = await _basesysroleRepository.QuerySingleData(m => m.id == userInfo.role);
            var result = RoleInfo.btnCodes;
            return new Message(result);
        }
    }
}
